if(!window.xflib || !window.xflib.client) window.xflib = { client: {} }

xflib.client.ProductService = class ProductService {

    constructor(storage) {
        this.storage = storage;
    }

    async create(productCode, productName) {
        if(productCode && productName){
            return this.storage.instance.get("products").then((data)=>{
                const products = data.products||{};
                if(Object.keys(products).includes(productCode) && products[productCode] === productName){
                    return Promise.reject("product already exists.");
                }
                return this.storage.instance.set({products:{...products, [productCode]: productName}});
            }).catch((error)=>{
                return Promise.reject(error.message);
            });
        }
        return Promise.reject("cannot null or empty products.");
    }

    async update(productOldCode, productCode, productName) {
        if(productCode && productName){
            return this.storage.instance.get("products").then((data)=>{
                const products = data.products||{};
                if(products && products[productOldCode]){
                    delete products[productOldCode];
                }
                return this.storage.instance.set({products: {...products, [productCode]: productName}});
            }).catch((error)=>{
                return Promise.reject(error.message);
            });
        }
        return Promise.reject("cannot null or empty products.");
    }

    async delete(productCodes) {
        if(productCodes){
            return this.storage.instance.get("products").then((data)=>{
                const products = data.products||{};
                this.toArray(productCodes).forEach((productCode,index)=>{
                    if(products && products[productCode]){
                        delete products[productCode];   
                    }
                });
                return this.storage.instance.set({products:products});
            }).catch((error)=>{
                return Promise.reject(error.message);
            });
        }
        return Promise.reject("cannot null or empty product codes.");
    }

    async clear() {
        return this.storage.instance.clear("products");
    }

    async queryByProductCodes(productCodes="products") {
        return this.storage.instance.get(productCodes).then((data)=>{
            return data.products;
        });
    }
    
    toArray(value) {
        if (value === null) return [];
        if (Array.isArray(value)) return value;
        return [value];
    }
}